// pages/admin/admin.js
const app = getApp()

Page({
  data: {
    originalHistory: [],
    filteredHistory: [],
    currentPage: 1,
    pageSize: 3,
    totalPages: 1,
    currentData: [],
    searchText: ''
  },

  onShow() {
    this.loadHistory()
  },

  loadHistory() {
    let originalHistory = wx.getStorageSync('history') || []
    originalHistory = originalHistory.map(item => {
      const entry = {
        user: item.user || '未知用户',
        formattedTime: item.formattedTime || '未知时间'
      };
      
      // 保留存在的字段
      if (item.hasOwnProperty('isDoorOpened')) {
        entry.isDoorOpened = !!item.isDoorOpened;
      }
      if (item.hasOwnProperty('isHeated')) {
        entry.isHeated = !!item.isHeated;
      }
      if (item.hasOwnProperty('newPassword')) {
        entry.newPassword = item.newPassword || '0000';
      }
      
      return entry;
    });
 
    this.setData({
      originalHistory,
      searchText: ''
    }, () => {
      this.filterHistory()
    })
  },

  filterHistory() {
    const { originalHistory, searchText } = this.data
    let filteredHistory = originalHistory
    
    if (searchText.trim()) {
      const keyword = searchText.toLowerCase()
      filteredHistory = originalHistory.filter(item => {
        const doorStatus = item.hasOwnProperty('isDoorOpened') 
          ? (item.isDoorOpened ? '开' : '关') 
          : ''
        const heatedStatus = item.hasOwnProperty('isHeated') 
          ? (item.isHeated ? '开' : '关') 
          : ''
        const password = item.hasOwnProperty('newPassword') 
          ? item.newPassword 
          : ''
        
        return (
          item.formattedTime.toLowerCase().includes(keyword) ||
          item.user.toLowerCase().includes(keyword) ||
          doorStatus.includes(keyword) ||
          heatedStatus.includes(keyword) ||
          password.includes(keyword)
        )
      })
    }

    const totalPages = Math.ceil(filteredHistory.length / this.data.pageSize) || 1
    
    this.setData({
      filteredHistory,
      totalPages,
      currentPage: Math.min(this.data.currentPage, totalPages)
    }, this.updateCurrentData)
  },

  updateCurrentData() {
    const { filteredHistory, currentPage, pageSize } = this.data
    const start = (currentPage - 1) * pageSize
    const end = start + pageSize
    
    this.setData({
      currentData: filteredHistory.slice(start, end)
    })
  },

  onSearchInput(e) {
    const searchText = e.detail.value
    this.setData({ searchText }, () => {
      this.filterHistory()
    })
  },

  confirmDelete() {
    wx.showModal({
      title: '警告',
      content: '此操作将删除历史记录，无法恢复，是否确认',
      success: (res) => {
        if (res.confirm) {
          app.clearHistory()
          this.loadHistory()
          wx.showToast({ title: '历史记录已清除' })
          
          const state = app.getCurrentState()
          this.setData({
            heaterStatus: state.isHeated,
            doorStatus: state.isDoorOpened,
            currentPassword: state.newPassword
          })
        }
      }
    })
  },

  prevPage() {
    if (this.data.currentPage > 1) {
      this.setData({
        currentPage: this.data.currentPage - 1
      }, this.updateCurrentData)
    }
  },

  nextPage() {
    if (this.data.currentPage < this.data.totalPages) {
      this.setData({
        currentPage: this.data.currentPage + 1
      }, this.updateCurrentData)
    }
  },

  gotonewpage() {
    wx.navigateTo({
      url: '/pages/admin/index'
    }) 
  }
})